<?php

namespace app\company\controller\statistics\rating_scale;

use app\BaseController;
use app\model\ProxyEvaluationResultModel;
use app\model\ProxyFactorScoreModel;
use app\model\RatingScaleFactorModel;
use app\model\RatingScaleLogModel;
use app\model\RatingScaleModel;
use app\model\SelfEvaluationResultModel;
use app\model\SelfFactorScoreModel;
use app\model\TaskFactorScoreModel;
use app\model\TaskUserResultModel;
use app\model\UserModel;
use app\model\WarningReportRecordModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 预警结果统计
     * @return bool|string
     */
    public function WarningPeopleNum(): bool|string
    {
        try {
            $WarningReportRecordModel = new WarningReportRecordModel();
            //今日
            $uids = $WarningReportRecordModel->where([
                ['unit_id','in',$this->userData['subset_unit']],
                ['time','>',strtotime(date("Y-m-d"))]
            ])->distinct(true)->column('uid');
            $data['day'] = count($uids);
            //历史
            $uids = $WarningReportRecordModel->where('unit_id','in',$this->userData['subset_unit'])->distinct(true)->column('uid');
            $data['history'] = count($uids);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 累计测评结果统计
     * @return bool|string
     */
    public function result(): bool|string
    {
        try {
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $data['wireless'] = 0;
            $data['task'] = $TaskUserResultModel->where('unit_id','in',$this->userData['subset_unit'])->count('id');
            $data['self'] = $SelfEvaluationResultModel->where('unit_id','in',$this->userData['subset_unit'])->count('id');
            $data['proxy'] = $ProxyEvaluationResultModel->where('unit_id','in',$this->userData['subset_unit'])->count('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 当月测评人数走势
     * @return bool|string
     */
    public function MonthTrend(): bool|string
    {
        try {
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $UserModel = new UserModel();
            $date = custom_time([date("Y-m-01"),date('Y-m-t')]);
            $data = [];
            foreach ($date as $item){
                $data['date'][] = $item['value'];
                $start_time = strtotime($item['start_time']);
                $end_time = strtotime($item['end_time']);
                $task = $TaskUserResultModel->where([
                    ['unit_id','in',$this->userData['subset_unit']],
                    ['time','between',[$start_time,$end_time]]
                ])->distinct(true)->column('uid');
                $self = $SelfEvaluationResultModel->where([
                    ['unit_id','in',$this->userData['subset_unit']],
                    ['time','between',[$start_time,$end_time]]
                ])->distinct(true)->column('uid');
                $proxy = $ProxyEvaluationResultModel->where([
                    ['unit_id','in',$this->userData['subset_unit']],
                    ['time','between',[$start_time,$end_time]]
                ])->distinct(true)->column('uid');
                $uids = array_merge($task,$self,$proxy);
                $uids = array_unique($uids);
                if (empty($uids)){
                    $data['boy'][] = 0;
                    $data['girl'][] = 0;
                    continue;
                }
                $total = count($uids);
                $boy = $UserModel->where([
                    ['id','in',$uids],
                    ['sex','=',1]
                ])->count('id');
                $girl = $total - $boy;
                $data['boy'][] = $boy;
                $data['girl'][] = $girl;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 累计综合数据统计
     * @return bool|string
     */
    public function comprehensive(): bool|string
    {
        try {
            $param = $this->request->param();
            $RatingScaleModel = new RatingScaleModel();
            $RatingScaleCount = $RatingScaleModel->where('unit_id','in',$this->userData['subset_unit'])->count('id');
            $RatingScaleLogModel = new RatingScaleLogModel();
            $data = $RatingScaleLogModel->where('unit_id','in',$this->userData['subset_unit'])->with([
                'RatingScale' => function ($query) {
                    $query->with(['ratingScaleTypeName']);
                },
                'user' => function ($query) {
                    $query->with(['unitName']);
                }
            ])->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item){
                $item['department_name'] = $item['unit_name'];
            }
            $log_num = $RatingScaleLogModel->where('unit_id','in',$this->userData['subset_unit'])->count('id');
            $people_num = $RatingScaleLogModel->where('unit_id','in',$this->userData['subset_unit'])->distinct(true)->count('uid');
            return success([
                'RatingScaleCount' => $RatingScaleCount,
                'people_num' => $people_num,
                'log_num' => $log_num,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 累计用户数量统计
     * @return bool|string
     */
    public function user(): bool|string
    {
        try {
            $UserModel = new UserModel();
            $RatingScaleLogModel = new RatingScaleLogModel();
            $uids = $RatingScaleLogModel->where('unit_id','in',$this->userData['subset_unit'])->distinct(true)->column('uid');
            $total = count($uids);
            $boy = $UserModel->where([
                ['id','in',$uids],
                ['sex','=',1]
            ])->count();
            $girl =$total - $boy;
            return success([
                'boy' => $boy,
                'girl' => $girl,
                'total' => $total
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * SCL-90指标统计
     * @return bool|string
     */
    public function scl90(): bool|string
    {
        try {
            $RatingScaleModel = new RatingScaleModel();
            $RatingScaleData = $RatingScaleModel->where([
                ['previous_name','=','症状自评量表（SCL-90）'],
                ['unit_id','in',$this->userData['subset_unit']]
            ])->field('id,mode_id')->select()->toArray();
            if(empty($RatingScaleData)) return success([
                'name' => [
                    "总分",
                    "总均分",
                    "躯体化",
                    "强迫症状",
                    "人际关系敏感",
                    "抑郁",
                    "焦虑",
                    "敌对",
                    "恐怖",
                    "偏执",
                    "精神病性",
                    "其他",
                    "阳性项目数",
                    "阳性症状均分"
                ],
                'num' => [
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0
                ]
            ]);
            $RatingScaleFactorModel = new RatingScaleFactorModel();
            $FactorData = [];
            foreach ($RatingScaleData as $item){
                $FactorIds = $RatingScaleFactorModel->where([
                    ['rating_scale_id','=',$item['id']],
                    ['mode_id','=',$item['mode_id']]
                ])->field('id,name')->select()->toArray();
                foreach ($FactorIds as $v){
                    $FactorData[$v['name']][] = $v['id'];
                }
            }
            $data = [];
            $TaskFactorScoreModel = new TaskFactorScoreModel();
            $SelfFactorScoreModel = new SelfFactorScoreModel();
            $ProxyFactorScoreModel = new ProxyFactorScoreModel();
            foreach ($FactorData as $key => $item){
                $data['name'][] = $key;
                $task = $TaskFactorScoreModel->where([
                    ['factor_id','in',$item],
                    ['is_warning','=',1]
                ])->count();
                $self = $SelfFactorScoreModel->where([
                    ['factor_id','in',$item],
                    ['is_warning','=',1]
                ])->count();
                $proxy = $ProxyFactorScoreModel->where([
                    ['factor_id','in',$item],
                    ['is_warning','=',1]
                ])->count();
                $data['num'][] = $task + $self + $proxy;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}